package com.zeus.base.smscenter.restful.api.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.smscenter.server.core.tradingcenter.TradingConsumExecutor;
import com.wordnik.swagger.annotations.ApiOperation;
import com.zeus.base.privilege.model.TbUser;
import com.zeus.base.privilege.service.IUserService;
import com.zeus.base.privilege.utils.DateUtil;
import com.zeus.base.privilege.utils.StringUtil;
import com.zeus.base.smscenter.model.SmsSupplierProperty;
import com.zeus.base.smscenter.model.Tenant;
import com.zeus.base.privilege.utils.ResultModel;
import com.zeus.base.smscenter.service.ISmsSettingService;
import com.zeus.base.smscenter.service.ISupplierPropertyService;
import com.zeus.base.tradingcenter.model.ConsumeBalance;
import com.zeus.base.tradingcenter.model.ConsumeType;
import com.zeus.base.tradingcenter.service.IConsumeBalanceService;
import com.zeus.base.tradingcenter.service.IConsumeTypeService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 查询接口(从交易中心查询短信账户余额等)
 * @author: liwenhua
 * @date： 2017年10月26日
 *
 */
@RestController
@RequestMapping("/tradingsmsquery")
public class TradingCenterQueryController {
    Logger log = Logger.getLogger(this.getClass());
    
    @Autowired
    private ISupplierPropertyService smsSupplierPropertyService;
    
    @Autowired
    private ISmsSettingService tenantService;

	@Autowired
	private IConsumeTypeService iConsumeTypeService;

	@Autowired
	private IUserService iUserService;

	@Autowired
	private IConsumeBalanceService iConsumeBalanceService;

    @RequestMapping(value = "/queryBalance", method = RequestMethod.POST)
    @ApiOperation(value = "短信帐户余额查询")
	public ResponseEntity<ResultModel> queryBalance(@RequestParam(value = "data") String data) {
		JSONObject obj = JSON.parseObject(data);
		String tenant = (String)obj.get("tenant");
		String authCenterPassword = (String)obj.get("authCenterPassword");
    	Map resMap = initResMap();//初始化返回,默认都为0
    	Tenant qt = new Tenant();
    	qt.setCode(tenant);
    	Tenant rst = tenantService.findByCode(qt);//查询用户信息
    	Double balance = 0.0;
    	if (rst != null) {
        	try {
				if (StringUtil.isEmpty(tenant) || StringUtil.isEmpty(authCenterPassword)) {
					return new ResponseEntity(new ResultModel(false, 101,"账号密码不能为空!"), HttpStatus.OK);
				}
				TbUser user = iUserService.getUserByLoginName(tenant);
				if (user == null || !authCenterPassword.equals(user.getLoginPwd())) {
					return new ResponseEntity(new ResultModel(false, 101,"账号密码不对!"), HttpStatus.OK);
				}
				if (user.getCompany() == null) {
					return new ResponseEntity(new ResultModel(false, 101,"用户公司信息不对!"), HttpStatus.OK);
				}
				ConsumeType consumeType = getConsumeType("短信");
				if (consumeType == null) {
					return new ResponseEntity(new ResultModel(false, 101,"交易中心消费项目不存在!"), HttpStatus.OK);
				}
				TradingConsumExecutor tradingConsumExecutor = new TradingConsumExecutor();
				ConsumeBalance consumeBalance = tradingConsumExecutor.getConsumeBalance(user.getCompany().getCompanyId(), consumeType.getConsumeTypeId(), iConsumeBalanceService);
				if (consumeBalance != null) {
					balance = consumeBalance.getBalance();
				}
				if (balance == null) {
					balance = 0d;
				}
				//查询短信,查询的是租户的默认通道,一个文字一个语音
				Map<String, Object> params = new HashMap<String, Object>();
				resMap = handleQueryBalance(resMap, rst, "sms", params,balance);//查询文字
				params.clear();
				resMap = handleQueryBalance(resMap, rst, "voice", params,balance);//查询语音
            }catch (Exception e){
                log.error(e.getMessage());
				return new ResponseEntity(new ResultModel(false, 201,e.getMessage()), HttpStatus.OK);
            }
		}else{
			return new ResponseEntity(new ResultModel(false, 101,"查无该租户"), HttpStatus.OK);
		}
		return new ResponseEntity(new ResultModel(true, 100,"成功",resMap), HttpStatus.OK);
    }


	private Map initResMap() {
		Map resMap = new HashMap();//返回map
    	resMap.put("sms_balance", "0");//剩余多少条
		resMap.put("sms_money", "0");//余额
		resMap.put("sms_supplier", "0");//通道
		resMap.put("voice_balance", "0");
		resMap.put("voice_money", "0");
		resMap.put("voice_supplier", "0");

		return resMap;
	}
	
	/**
	 * 通用调查询接口,将返回的值分类型放至返回的map里
	 * @param resMap 反回map
	 * @param rst 租户
	 * @param type 类型二选一     sms为文字  voice为语音
	 * @param params 参数map
	 * @param balance 余额
	 * @return
	 * @throws Exception
	 */
	private Map handleQueryBalance(Map resMap, Tenant rst, String type,Map<String, Object> params,Double balance) throws Exception {
		String supplierNo = null;//通道
		if ("VOICE".equals(type.toUpperCase())) {//如果是语音,取语音的通道
			supplierNo = rst.getDefaultVoiceSupplierNo();
		} else {
			supplierNo = rst.getDefaultSmsSupplierNo();
		}
		params.put("code", rst.getCode());
		params.put("supplierNo", supplierNo);
		double unitPrice = 0.0;
		List<SmsSupplierProperty> smsSupplierPropertyList = smsSupplierPropertyService.find(params);
		if (smsSupplierPropertyList != null && smsSupplierPropertyList.size() > 0) {
			for (SmsSupplierProperty smsSupplierProperty : smsSupplierPropertyList) {
		        params.put(smsSupplierProperty.getPropertyName(), smsSupplierProperty.getPropertyValue());
		    }
			params.put("sendType", type.toUpperCase());

			resMap.put(type.toLowerCase() + "_supplier", supplierNo);//通道

			if ("SMS".equals(params.get("sendType"))) {//如果是查询的文字的取文字价格
				unitPrice = Double.parseDouble(params.get("unitPrice")+"");
			} else if ("VOICE".equals(params.get("sendType"))) {
				unitPrice = Double.parseDouble(params.get("voiceUnitPrice")+"");
			}

	    	resMap.put(type.toLowerCase() + "_balance", String.valueOf((int)(balance/unitPrice)));//剩余多少条
			resMap.put(type.toLowerCase() + "_money", String.valueOf(balance));//余额
		}
		return resMap;
	}


	private static HashMap<String, HashMap<String, Object>> cacheTypeMap = new HashMap<String, HashMap<String, Object>>();
	private ConsumeType getConsumeType(String type) {
		HashMap<String, Object> cacheParams = cacheTypeMap.get(type);
		ConsumeType consumeType = null;
		if (cacheParams != null) {
			Date time = (Date) cacheParams.get("time");
			if (DateUtil.getDistanceOfTwoMinite(time, new Date()) < 180) {//缓存时间为180分钟
				consumeType = (ConsumeType) cacheParams.get("consumeType");
			}
		}
		if (consumeType == null) {
			HashMap<String, Object> params = new HashMap<String, Object>();
			params.put("consumeTypeName", type);
			List<ConsumeType> consumeTypes = iConsumeTypeService.findList(params);
			if (consumeTypes.size() == 0) {
				return null;
			}
			consumeType = consumeTypes.get(0);
			consumeType.setListSet(iConsumeTypeService.findConsumeTypeSet(consumeType.getConsumeTypeId()));
			cacheParams = new HashMap<String, Object>();
			cacheParams.put("time", new Date());
			cacheParams.put("consumeType", consumeType);
			cacheTypeMap.put(type, cacheParams);
		}
		return consumeType;
	}

}

